package com.sunmouse.toollib.utils.load;

import android.os.Handler;
import android.os.Message;

import com.sunmouse.toollib.constants.Load;
import com.sunmouse.toollib.utils.LogUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class MultiLoadTask extends Thread {
    private LoadRequest mRequest;
    private int position;
    private Handler mHandler;
    private Message msg;


    @Override
    public void run() {
        super.run();
        try {
            //long cp = 0;
            URL url = new URL(mRequest.getRemoteUrl());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setAllowUserInteraction(true);
            conn.setRequestProperty("Range", "bytes=" + mRequest.getStart() + "-" + mRequest.getEnd());
            int status = conn.getResponseCode();
            LogUtils.v("status=" + status);
            if (conn.getResponseCode() == 206) {//partial content
                BufferedInputStream bis = new BufferedInputStream(
                        conn.getInputStream());
                RandomAccessFile rafOut = new RandomAccessFile(mRequest.getOutFile(), "rw");
                // bis.mark((int) start);
                // bis.skip(start);
                rafOut.seek(mRequest.getStart());
                LogUtils.v("task", "--start=" + mRequest.getStart());
                int len = 0;
                byte[] b = new byte[LoadUtils.READ_SIZE];
                while ((len = bis.read(b)) != -1) {
                    rafOut.write(b, 0, len);
                    //send loaded length
                    sendMsg(Load.LOADING, len, position, 0);
//                    LogUtils.v("loading...");
                    if (mRequest.isStop()) {
                        sendMsg(Load.STOP, 0, position);
                        break;
                    }
                }
                rafOut.close();
                bis.close();
                conn.disconnect();
                if (!mRequest.isStop())
                    sendMsg(Load.COMPLETE, 0, position);
            }
        } catch (IOException e) {
            e.printStackTrace();
            sendMsg(Load.STOP, 0, position);
        }

    }

    /**
     * send msg
     * read
     */
    private void sendMsg(int status, int read, int position, long delay) {
        msg = Message.obtain();
        msg.what = status;
        msg.arg1 = read;
        msg.arg2 = position;
        mHandler.sendMessageDelayed(msg, delay);
    }

    private void sendMsg(int status, int read, int position) {
        this.sendMsg(status, read, position, 0);
    }

    public MultiLoadTask(LoadRequest request, Handler mHandler, int position) {
        super();
        if (request == null) {
            throw new RuntimeException("Error request is invalid");
        }
        this.mRequest = request;
        this.mHandler = mHandler;
        this.position = position;
    }

    /**
     * a task factory
     */
    public static MultiLoadTask newTask(LoadRequest request, Handler mHandler, int position) {
        return new MultiLoadTask(request, mHandler, position);
    }
}
